package org.example.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @Program: qiyu-live-app
 * @Description: [7.8] NIO代码实战讲解
 * @Author: tangfh
 * @Create: 2024-07-16 09:32
 */
public class NioServer {

    private static List<SocketChannel> channelList = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket socket = serverSocketChannel.socket();
        socket.bind(new InetSocketAddress(9090));
        serverSocketChannel.configureBlocking(false);
        new Thread(() -> {
            while (true) {
                // 缺点分析：假设有10000个channel，没有消息传递过来，for循环一直空轮训，导致cup占用会比较高
                for (SocketChannel channel : channelList) {
                    ByteBuffer dst = ByteBuffer.allocate(10);
                    try {
                        // 非阻塞调用
                        channel.read(dst);
                        System.out.println("服务端接受数据："+ new String(dst.array()));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        // 非阻塞调用
        while (true) {
            SocketChannel channel = serverSocketChannel.accept();
            if (channel != null) {
                System.out.println("建立连接");
                channel.configureBlocking(false);
                channelList.add(channel);
            }
        }
    }
}
